<?php

namespace app\home\controller;

use app\company\service\DataService;
use library\Controller;
use think\Db;
use app\common\controller\Common;

/**
 * 运营计划管理
 * Class User
 * @package app\worker\controller
 */
class Plan extends Controller
{
    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'Plan';

    /**
     * 运营计划管理
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '运营计划管理';
        $query = $this->_query($this->table)
            ->alias('p')
            ->join('ware_house wh', 'wh.id = p.ware_house_id', 'left')
            ->dateBetween('p.create_at#create_at')
            ->where(['p.is_deleted' => '0']);
        if(session('user.ware_house_id')){
            $query->where('p.ware_house_id', session('user.ware_house_id')); 
        }
        if(request()->get('ware_house_id')){
            $query->where('p.ware_house_id', request()->get('ware_house_id'));
            //修改该仓库的所有运营计划为已查看
            Db::name('Plan')->where('ware_house_id', request()->get('ware_house_id'))->update(['is_new' => 0]);
        }
        $query->like('wh.name#name')
            ->equal('p.status#status')
            ->field('wh.name,p.*')
            ->order('p.plan_date desc')
            ->page();
    }

    protected function _index_page_filter(&$data) {
        //判断当前用户是否有审批权限
        Common::get_is_check($this->table, $data);
    }

    /**
     * 添加运营计划
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->_form($this->table, 'form');
    }

    public function _add_form_result(&$id)
    {
        $this->add_plan_detail($id);
        //生成审批流
        Common::set_check($this->table, $id);
    }

    /**
     * 修改运营计划
     * @auth true
     */
    public function edit()
    {
        $this->_form($this->table, 'form');
    }

    public function _edit_form_result(&$id)
    {
        $this->add_plan_detail($id);
    }

    /**
     * 权限表单数据处理
     * @param array $data 表单数据
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
        //获取仓库表
        $where = [
            ['is_deleted', '=', 0],
            ['status', '=', 1],
        ];
        if(session('user.ware_house_id')){
           $where[] = ['id', '=', session('user.ware_house_id')];
        }
        $this->ware_house = Db::name('WareHouse')->where($where)->order('sort desc')->select();
        foreach($this->ware_house as &$v){
            //岗位 0有车 1无车 2标品 3冻品 4大件 5杂工
            $price_rules = Db::name('PriceRules')
                ->where('platform_id', $v['platform_id'])
                ->where('city_level', $v['city_level'])
                ->where('is_deleted', 0)
                ->column('jobs,price');
            //有车价格
            $v['ca_have_price'] = $price_rules[0];
            //无车价格
            $v['ca_no_price'] = $price_rules[1];
            //标品价格
            $v['so_pure_price'] = $price_rules[2];
            //冻品价格
            $v['so_frozen_price'] = $price_rules[3];
            //大件价格
            $v['so_big_price'] = $price_rules[4];
            //杂工价格
            $v['so_handyman_price'] = $price_rules[5];
        }
        
        if (request()->isPost()) {
            //一个仓库不能存在两个相同履约日期的运营计划
            $where = [
                ['ware_house_id', '=', $data['ware_house_id']],
                ['is_deleted', '=', 0],
                ['plan_date', '=', $data['plan_date']]
            ];
            if (isset($data['id'])) {
                $where[] = ['id', '<>', $data['id']];
            }
            $plan = Db::name($this->table)->where($where)->find();
            if ($plan) {
                $this->error('该仓库所选履约日期已存在运营计划');
            }
            //判断是否添加了前一天的运营计划
            $before_date = date('Y-m-d', strtotime($data['plan_date']) - 3600 * 24);
            $where = [
                ['ware_house_id', '=', $data['ware_house_id']],
                ['is_deleted', '=', 0],
                ['plan_date', '<=', $data['plan_date']]
            ];
            if (isset($data['id'])) {
                $where[] = ['id', '<>', $data['id']];
                $ware_house_id = Db::name($this->table)
                    ->where('id', $data['id'])
                    ->order('plan_date desc')
                    ->value('ware_house_id');
            }
            $plan_date = Db::name($this->table)
                ->where($where)
                ->order('plan_date desc')
                ->value('plan_date');
            //不修改仓库
            if (!empty($plan_date) && $plan_date != $before_date) {
                $this->error('该仓库所选履约日期前一天的运营计划缺失，请先补充');
            }
            //修改仓库
            if (!empty($plan_date) && $plan_date != $before_date && $ware_house_id != $data['ware_house_id']) {
                $this->error('该仓库所选履约日期前一天的运营计划缺失，请先补充');
            }

            //保存首次录入人username
            if (!isset($data['id']) || !Db::name($this->table)->where('id', $data['id'])->value('username')) {
                $data['username'] = session('user.username');
            }
            $car_sum = 0;
            $man_sum = 0;
            $ca_fixed = [];
            $ca_temporary = [];
            $so_fixed = [];
            $so_temporary = [];
            $ware_house = Db::name('ware_house')->where('id', $data['ware_house_id'])->find();
            //运力需求明细
            if (isset($data['ca_fixed']['count']) && !empty($data['ca_fixed']['count'])) {
                foreach ($data['ca_fixed']['count'] as $k => $v) {
                    $ca_fixed[] = [
                        'jobs' => $data['ca_fixed']['jobs'][$k],
                        'att' => $data['ca_fixed']['att'][$k],
                        'payment_way' => $data['ca_fixed']['payment_way'][$k],
                        'classify' => $data['ca_fixed']['payment_way'][$k] ? 0 : 1,
                        'count' => $data['ca_fixed']['count'][$k],
                        'is_rate' => $data['ca_fixed']['is_rate'][$k],
                        'price' => $data['ca_fixed']['price'][$k],
                        'subsidy' => Db::name('PriceRules')->where('is_deleted', 0)
                                ->where('city_level', $ware_house['city_level'])
                                ->where('platform_id', $ware_house['platform_id'])
                                ->where('jobs', $data['ca_fixed']['jobs'][$k])
                                ->value('subsidy')//日补贴
                    ];
                    $car_sum += $data['ca_fixed']['count'][$k];
                }
                $data['ca_fixed'] = json_encode($ca_fixed);
            } else {
                $this->error('运力需求明细不能为空');
            }
            //运力需求新增
            if (isset($data['ca_temporary']['count']) && !empty($data['ca_temporary']['count'])) {
                foreach ($data['ca_temporary']['count'] as $k => $v) {
                    if($data['ca_temporary']['count'][$k]){
                        $ca_temporary[] = [
                            'jobs' => $data['ca_temporary']['jobs'][$k],
                            'att' => $data['ca_temporary']['att'][$k],
                            'payment_way' => $data['ca_temporary']['payment_way'][$k],
                            'classify' => $data['ca_temporary']['payment_way'][$k] ? 0 : 1,
                            'count' => $data['ca_temporary']['count'][$k],
                            'is_rate' => $data['ca_temporary']['is_rate'][$k],
                            'price' => $data['ca_temporary']['price'][$k],
                            'reason' => $data['ca_temporary']['reason'][$k],
                            'subsidy' => Db::name('PriceRules')->where('is_deleted', 0)
                                ->where('city_level', $ware_house['city_level'])
                                ->where('platform_id', $ware_house['platform_id'])
                                ->where('jobs', $data['ca_temporary']['jobs'][$k])
                                ->value('subsidy')
                        ];
                    }
                }
                $data['ca_temporary'] = json_encode($ca_temporary);
            }else{
                $data['ca_temporary'] = '';
            }
            //分拣需求明细
            if (isset($data['so_fixed']['count']) && !empty($data['so_fixed']['count'])) {
                foreach ($data['so_fixed']['count'] as $k => $v) {
                    $so_fixed[] = [
                        'jobs' => $data['so_fixed']['jobs'][$k],
                        'att' => $data['so_fixed']['att'][$k],
                        'payment_way' => $data['so_fixed']['payment_way'][$k],
                        'classify' => $data['so_fixed']['payment_way'][$k] ? 0 : 1,
                        'count' => $data['so_fixed']['count'][$k],
                        'is_rate' => $data['so_fixed']['is_rate'][$k],
                        'price' => $data['so_fixed']['price'][$k],
                        'subsidy' => Db::name('PriceRules')->where('is_deleted', 0)
                                ->where('city_level', $ware_house['city_level'])
                                ->where('platform_id', $ware_house['platform_id'])
                                ->where('jobs', $data['so_fixed']['jobs'][$k])
                                ->value('subsidy')
                    ];
                    $man_sum += $data['so_fixed']['count'][$k];
                }
                
                $data['so_fixed'] = json_encode($so_fixed);
            } else {
                $this->error('分拣需求明细不能为空');
            }
            //分拣需求新增
            if (isset($data['so_temporary']['count']) && !empty($data['so_temporary']['count'])) {
                foreach ($data['so_temporary']['count'] as $k => $v) {
                    if($data['so_temporary']['count'][$k]){
                        $so_temporary[] = [
                            'jobs' => $data['so_temporary']['jobs'][$k],
                            'att' => $data['so_temporary']['att'][$k],
                            'payment_way' => $data['so_temporary']['payment_way'][$k],
                            'classify' => $data['so_temporary']['payment_way'][$k] ? 0 : 1,
                            'count' => $data['so_temporary']['count'][$k],
                            'is_rate' => $data['so_temporary']['is_rate'][$k],
                            'price' => $data['so_temporary']['price'][$k],
                            'reason' => $data['so_temporary']['reason'][$k],
                            'subsidy' => Db::name('PriceRules')->where('is_deleted', 0)
                                ->where('city_level', $ware_house['city_level'])
                                ->where('platform_id', $ware_house['platform_id'])
                                ->where('jobs', $data['so_temporary']['jobs'][$k])
                                ->value('subsidy')
                        ];
                    }
                }
                $data['so_temporary'] = json_encode($so_temporary);
            }else{
                $data['so_temporary'] = '';
            }
            //运力车辆数不能大于计划车辆数
            if ($car_sum > $data['car_number']) {
                $this->error('运力车辆数总和不能大于计划车辆数');
            }
            //分拣人数不能大于计划分拣人数
            if ($man_sum > $data['man_number']) {
                $this->error('分拣人数总和不能大于计划分拣人数');
            }
        } else {
            if (isset($data['ca_fixed'])) $data['ca_fixed'] = json_decode($data['ca_fixed'], true);
            if (isset($data['ca_temporary'])) $data['ca_temporary'] = json_decode($data['ca_temporary'], true);
            if (isset($data['so_fixed'])) $data['so_fixed'] = json_decode($data['so_fixed'], true);
            if (isset($data['so_temporary'])) $data['so_temporary'] = json_decode($data['so_temporary'], true);
        }
    }

    //添加运营计划明细
    public function add_plan_detail($id)
    {
        $plan = Db::name($this->table)->where('id', $id)->find();
        $plan['ca_fixed'] = $plan['ca_fixed'] ? json_decode($plan['ca_fixed'], true) : [];
        $plan['ca_temporary'] = $plan['ca_temporary'] ? json_decode($plan['ca_temporary'], true) : [];
        $plan['so_fixed'] = $plan['so_fixed'] ? json_decode($plan['so_fixed'], true) : [];
        $plan['so_temporary'] = $plan['so_temporary'] ? json_decode($plan['so_temporary'], true) : [];
        $plan_detail = [];
        foreach ($plan['ca_fixed'] as $v) {
            $plan_detail[] = [
                'type' => 0,
                'classify' => $v['classify'],
                'att' => $v['att'],
                'payment_way' => $v['payment_way'],
                'price' => $v['price'],
                'count' => $v['count'],
                'jobs' => $v['jobs'],
                'is_rate' => $v['is_rate'],
                'subsidy' => $v['subsidy'],
                'reason' => '',
                'plan_id' => $id
                
            ];
        }
        foreach ($plan['ca_temporary'] as $v) {
            $plan_detail[] = [
                'type' => 0,
                'classify' => $v['classify'],
                'att' => $v['att'],
                'payment_way' => $v['payment_way'],
                'price' => $v['price'],
                'count' => $v['count'],
                'jobs' => $v['jobs'],
                'is_rate' => $v['is_rate'],
                'subsidy' => $v['subsidy'],
                'reason' => $v['reason'],
                'plan_id' => $id
            ];
        }
        foreach ($plan['so_fixed'] as $v) {
            $plan_detail[] = [
                'type' => 1,
                'classify' => $v['classify'],
                'att' => $v['att'],
                'payment_way' => $v['payment_way'],
                'price' => $v['price'],
                'count' => $v['count'],
                'jobs' => $v['jobs'],
                'is_rate' => $v['is_rate'],
                'subsidy' => $v['subsidy'],
                'reason' => '',
                'plan_id' => $id
            ];
        }
        foreach ($plan['so_temporary'] as $v) {
            $plan_detail[] = [
                'type' => 1,
                'classify' => $v['classify'],
                'att' => $v['att'],
                'payment_way' => $v['payment_way'],
                'price' => $v['price'],
                'count' => $v['count'],
                'jobs' => $v['jobs'],
                'is_rate' => $v['is_rate'],
                'subsidy' => $v['subsidy'],
                'reason' => $v['reason'],
                'plan_id' => $id
            ];
        }
        //删除旧数据
        Db::name('PlanDetail')->where('plan_id', $plan['id'])->delete();
        //添加新数据
        Db::name('PlanDetail')->insertAll($plan_detail);
    }

    /**
     * 删除运营计划
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 基础收入信息查看权限
     * @auth true
     */
    public function look_income()
    {
    }

    /**
     * 审批通过
     */
    public function check()
    {
        Common::check($this->table);
        $this->success('审核通过');
    }

    /**
     * 查看审批流
     * @auth true
     */
    public function get_check()
    {
        $table = $this->table;
        $id = request()->get('id');
        $res = Common::get_check($table, $id);
        $this->data = $res['data'];
        $this->cc_mans = $res['cc_mans'];
        $this->fetch();
    }
}
